package servlets;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

/**
 * Created by hadoop on 17-6-15.
 * 处理文件上传的Servlet
 */
@WebServlet(name = "UploadServlet",urlPatterns = {"/UploadServlet"})
@MultipartConfig
public class UploadServlet extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext application = req.getServletContext();
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        req.setCharacterEncoding("utf-8");
        String name = req.getParameter("name");
        out.println("普通的name参数: "+name+"<br>");
        //获取文件Part对象
        Part part = req.getPart("file");
        out.println("上传文件的类型:"+part.getContentType()+"<br>");
        out.println("上传文件的大小:"+part.getSize()+"<br>");
        out.println("上传文件的大小:"+part.getSize()+"<br>");
        Collection<String> headerNames = part.getHeaderNames();
        for(String s : headerNames){
            out.println(s+"==>"+part.getHeader(s)+"<br>");
        }
        String fileNameInfo = part.getHeader("content-disposition");
        String fileName = fileNameInfo.substring(fileNameInfo.indexOf("filename=\"")+10,fileNameInfo.length()-1);
        out.println("文件名: "+fileName+"<br>");
        String path = application.getRealPath("/uploadFiles");
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        out.println("getRealPatt(\"/uploadFiles\"): "+path+"<br>");
        //写入文件
        part.write(path+"/"+fileName);
    }
}
